﻿/// <reference path="typings/sharepoint/sharepoint.d.ts" />
/// <reference path="typings/jquery/jquery.d.ts" />

'use strict';

ExecuteOrDelayUntilScriptLoaded(initializePage, "sp.js");

var ANNOUNCEMENT_LIST_NAME = "New Announcements List";

var _operations: ListOperations;

function initializePage() {

    $(document).ready(function () {
        _operations = new ListOperations();
    });

}

function btnOperationOnClick() {
    switch ($('#optList').val()) {
        case "Get All Announcement Lists":
            _operations.listObjects();
            break;
        case "Add a new Announcement List":
            _operations.addObject(ANNOUNCEMENT_LIST_NAME);
            break;
        case "Update Announcement List":
            _operations.updateObject(ANNOUNCEMENT_LIST_NAME);
            break;
        case "Delete First Announcement List":
            _operations.deleteObject(ANNOUNCEMENT_LIST_NAME);
            break;
        default:
            console.log("invalid case");
    }
}

interface BasicCRUD {
    listObjects(): void;
    addObject(title: string): void;
    updateObject(title: string): void;
    deleteObject(title: string): void;
}

interface Logger {
    logError(sender: any, e: SP.ClientRequestFailedEventArgs): void;
}

class Operations {
    public OperationType: string;

    constructor(operationType: string) {
        this.OperationType = operationType;
    }
}

class WebOperations extends Operations implements BasicCRUD, Logger {
    constructor() {
        super("Web Operations");
    }

    listObjects() { }
    addObject(title: string) { }
    updateObject(title: string) { }
    deleteObject(title: string) { }

    logError(sender, args) { }
}

class ListOperations extends Operations implements BasicCRUD, Logger {

    private _currentContext: SP.ClientContext;
    private _hostContext: SP.AppContextSite;
    private _webSite: SP.Web;
    private _collList: SP.ListCollection;
    private _list: SP.List;

    constructor() {
        super("List Operations");

        var hostUrl = decodeURIComponent(this.getQueryStringParameter("SPHostUrl"));

        this._currentContext = SP.ClientContext.get_current();
        this._hostContext = new SP.AppContextSite(this._currentContext, hostUrl);

        this._webSite = this._hostContext.get_web();
    }

    listObjects() {
        $('#message').text("fetching announcement lists...");

        this._collList = this._webSite.get_lists();

        this._currentContext.load(this._collList);//, 'Include(Title, Id)');
        this._currentContext.executeQueryAsync(
            () => this._onlistObjectsSucceeded(),
            (s: any, e: SP.ClientRequestFailedEventArgs) => this.logError(this, e)
        );
    }

    private _onlistObjectsSucceeded() {
        var listInfo = '';
        var listEnumerator = this._collList.getEnumerator();

        while (listEnumerator.moveNext()) {
            var list = listEnumerator.get_current();
            var listTemplateType = list.get_baseTemplate();
            if (listTemplateType === SP.ListTemplateType.announcements) {
                listInfo += 'Title: ' + list.get_title() + " " + "<br/>";
                listInfo += 'Description: ' + list.get_description() + " " + "<br/><br/>";
            }
        }
        $('#message').html(listInfo);
    }

    logError(sender, args) {
        $('#message').text('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
    }

    addObject(listName: string) {

        $('#message').text("creating announcement list...");

        var listCreationInfo = new SP.ListCreationInformation();
        listCreationInfo.set_title(listName);
        listCreationInfo.set_templateType(SP.ListTemplateType.announcements);

        this._list = this._webSite.get_lists().add(listCreationInfo);
        this._currentContext.load(this._list);

        this._currentContext.executeQueryAsync(
            () => this._onAddObjectSucceeded(),
            (s: any, e: SP.ClientRequestFailedEventArgs) => this.logError(this, e)
        );
    }

    private _onAddObjectSucceeded() {
        var result = ANNOUNCEMENT_LIST_NAME + ' created.';
        $('#message').text(result);
    }

    updateObject(listName: string) {

        $('#message').text("updating announcement list...");

        this._list = this._webSite.get_lists().getByTitle(listName);
        this._list.set_description(listName + " ---updated");
        this._list.update();
        this._currentContext.load(this._list);

        this._currentContext.executeQueryAsync(
            () => this._onUpdateObjectSucceeded(),
            (s: any, e: SP.ClientRequestFailedEventArgs) => this.logError(this, e)
        );
    }

    private _onUpdateObjectSucceeded() {
        var result = ANNOUNCEMENT_LIST_NAME + ' updated.';
        $('#message').text(result);
    }

    deleteObject(listName: string) {

        $('#message').text("deleting announcement list...");

        this._list = this._webSite.get_lists().getByTitle(listName);
        this._list.deleteObject();

        this._currentContext.executeQueryAsync(
            () => this._onDeleteObjectSucceeded(),
            (s: any, e: SP.ClientRequestFailedEventArgs) => this.logError(this, e)
        );
    }

    private _onDeleteObjectSucceeded() {
        var result = ANNOUNCEMENT_LIST_NAME + ' deleted.';
        $('#message').text(result);
    }


    private getQueryStringParameter(paramToRetrieve) {
        var params = document.URL.split("?")[1].split("&");
        var strParams = "";

        for (var i = 0; i < params.length; i = i + 1) {
            var singleParam = params[i].split("=");
            if (singleParam[0] == paramToRetrieve)
                return singleParam[1];
        }
    }
}
